﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Twinkle.Dialogs.Hashtag
{
    public partial class HashtagSelector : Form
    {
        public HashtagSelector(string tags)
        {
            InitializeComponent();
            hashtags.Items.AddRange(Kernel.Storage.GetHashtags().ToArray());
            if (tags != null)
            {
                var tgs = from t in tags.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries)
                          select t.TrimStart('#');
                foreach (var t in tgs)
                {
                    int idx = -1;
                    if ((idx = hashtags.Items.IndexOf(t)) >= 0)
                    {
                        hashtags.SetItemChecked(idx, true);
                    }
                }
            }
        }

        public bool AutoBindEditable
        {
            get { return editAutoBinding.Visible; }
            set { editAutoBinding.Visible = value; }
        }

        public string Hashtags
        {
            get
            {
                var tags = from t in hashtags.CheckedItems.Cast<string>()
                           select "#" + t;
                return String.Join(" ", tags.ToArray());
            }
        }

        private void checkAll_Click(object sender, EventArgs e)
        {
            for(int i = 0; i < hashtags.Items.Count; i++)
            {
                hashtags.SetItemChecked(i, true);
            }
        }

        private void uncheckAll_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < hashtags.Items.Count; i++)
            {
                hashtags.SetItemChecked(i, false);
            }
        }

        private void addHashtag_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(addTagText.Text))
            {
                var splits = addTagText.Text.Split(new[] { "#" }, StringSplitOptions.RemoveEmptyEntries);
                foreach(var tag in splits)
                {
                    if (!hashtags.Items.Contains(addTagText))
                    {
                        if (Kernel.Storage.AddHashtag(addTagText.Text))
                            hashtags.Items.Add(addTagText.Text);
                    }
                }
            }
            addTagText.Text = string.Empty;
        }

        private void editAutoBinding_Click(object sender, EventArgs e)
        {
            using (var editor = new BindingConfig())
            {
                editor.ShowDialog();
            }
        }
    }
}
